#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/5/27 14:59
# @Author : wn 
# @File: makemarketpara.py
# @SoftWare: PyCharm
# @Site:
# @Table:
# ｡◕‿◕｡｡◕‿◕｡｡◕‿◕｡


from django.shortcuts import render, HttpResponse, redirect
from Manager.models import *
from Rbac.models import *
from Manager.views.service import my_page
from django.http import JsonResponse
import json
from Django_Admin.enumType import *

from Rbac.utils.login_deco import *


@auth
def makemarketpara_list(request):
    # 当前在第几页
    off = request.GET.get('offset', None)
    # 一页几条数据
    lim = request.GET.get('limit', None)
    # 获取url后拼接的search
    search = request.GET.get('search', None)
    # 分账号代码需要一个实例
    crr = Customerchannelrel.objects.exclude(combino="").values("accountid", "combino")
    # 判断url后面是否拼接了search，没有，返回页面；有显示搜索条件的值
    if search is None:
        return render(request, 'makemarketpara.html', {'crr': crr})
    else:
        # 按搜索条件获取值
        if search:
            # 如果多个主键，这filter中，连写另一个值可以吗
            mmp_list = Makemarketpara.objects.values().filter(instrumentid__contains=search)
        else:
            mmp_list = Makemarketpara.objects.values()
        # 把queryset转成列表[{},{}]
        mmp_list = list(mmp_list)
        # print(mmp_list)
        for item in mmp_list:
            # 联合主键，用id
            item['option'] = item['id']
            # 枚举值
            item['exchangeid'] = Exchangeid_choices.get(item['exchangeid'], None)
            item['isinvolved'] = IsInvolved_choices.get(item['isinvolved'], None)
        result = my_page(mmp_list, lim, off)
        return JsonResponse(result, safe=False)


# 添加，修改，删除
def makemarketpara_modify(request):
    ##拿到登录用户id
    userid = request.session["id"]
    isdelete = Customer.objects.filter(customerid=userid).filter(
        roles__permissions__url__endswith='makemarketpara_list(delete)')
    ismodify = Customer.objects.filter(customerid=userid).filter(
        roles__permissions__url__endswith='makemarketpara_list(modify)')
    isadd = Customer.objects.filter(customerid=userid).filter(
        roles__permissions__url__endswith='makemarketpara_list(add)')
    if request.method == 'GET':
        # 联合主键，联合主键用id判断记录的唯一性
        mmp_id = request.GET['id']
        item = Makemarketpara.objects.values().filter(id=mmp_id).first()
        item["exchangeid"] = exchangeid_alter[item["exchangeid"]]
        # print('被修改的值：', item)
        if item:
            return JsonResponse(item, safe=False)
    else:
        if request.POST.get('delete', None):
            if isdelete:
                # 删除
                mmpid = request.POST.get('id')
                try:
                    Makemarketpara.objects.filter(id=mmpid).delete()
                    return HttpResponse('y')
                except Exception as e:
                    print(e)
                return HttpResponse("y")
            else:
                return HttpResponse("该用户无操作权限")
        else:
            data = request.POST
            '''
            get Customerchannelrel object <class 'Manager.models.Customerchannelrel'>
            filter <QuerySet [<Customerchannelrel: Customerchannelrel object>]> <class 'django.db.models.query.QuerySet'>
            '''
            try:
                if json.loads((data['id']))[0]:
                    if ismodify:
                        if Makemarketpara.objects.filter(id=json.loads(data['id'])[0]).count() >= 1:
                            # 分账户代码是唯一的，直接用它去查分账户对象
                            accountid = json.loads(data["accountid"])[0]
                            crr_accountid = Customerchannelrel.objects.get(accountid=accountid)

                            Makemarketpara.objects.filter(id=json.loads(data['id'])[0]).update(
                                instrumentid=json.loads(data["instrumentid"])[0],
                                exchangeid=MarketCodeDesc.get(json.loads(data["exchangeid"])[0]),
                                isinvolved=json.loads(data["isinvolved"])[0],
                                buypricespread=json.loads(data["buypricespread"])[0],
                                sellpricespread=json.loads(data["sellpricespread"])[0],
                                buyvolume=json.loads(data["buyvolume"])[0],
                                sellvolume=json.loads(data["sellvolume"])[0],
                                minbuyvolume=json.loads(data["minbuyvolume"])[0],
                                minsellvolume=json.loads(data["minsellvolume"])[0],
                                maxspread=json.loads(data["maxspread"])[0],
                                accountid=crr_accountid,
                                combino=json.loads(data["combino"])[0],
                            )
                            return HttpResponse('y')
                    else:
                        return HttpResponse("该用户无操作权限！")
                else:
                    if isadd:
                        # 新增

                        # 根据合约代码和持仓账号唯一确认策略参数，如果已经存在，alert
                        mpobj2 = Makemarketpara.objects.filter(
                            instrumentid=json.loads(data["instrumentid"])[0],
                            combino=json.loads(data["combino"])[0]
                        )
                        # mpobj1 = Makemarketpara.objects.filter(
                        #     instrumentid=json.loads(data['instrumentid'])[0]
                        # )
                        if mpobj2:
                            return HttpResponse("合约做市参数已存在！")

                        accountid = json.loads(data["accountid"])[0]
                        # 根据持仓账号和分账户代码唯一确定分账户对象
                        crr_accountid = Customerchannelrel.objects.get(accountid=accountid,
                                                                       combino=json.loads(data["combino"])[0])

                        Makemarketpara.objects.create(
                            instrumentid=json.loads(data["instrumentid"])[0],
                            exchangeid=MarketCodeDesc.get(json.loads(data["exchangeid"])[0]),
                            isinvolved=json.loads(data["isinvolved"])[0],
                            buypricespread=json.loads(data["buypricespread"])[0],
                            sellpricespread=json.loads(data["sellpricespread"])[0],
                            buyvolume=json.loads(data["buyvolume"])[0],
                            sellvolume=json.loads(data["sellvolume"])[0],
                            minbuyvolume=json.loads(data["minbuyvolume"])[0],
                            minsellvolume=json.loads(data["minsellvolume"])[0],
                            maxspread=json.loads(data["maxspread"])[0],
                            accountid=crr_accountid,
                            combino=json.loads(data["combino"])[0],
                        )

                        # 在新增合约做市参数记录的同时新增合约做市状态记录，取TMakemarketpara（合约做市参数）的InstrumentID/ AccountID/ CombiNo
                        tmms = Makemarketstatus()
                        tmms.instrumentid = json.loads(data["instrumentid"])[0]
                        tmms.accountid = crr_accountid.accountid
                        tmms.combino = json.loads(data["combino"])[0]
                        tmms.status = 0
                        tmms.buystatus = 0
                        tmms.sellstatus = 0
                        tmms.lastrectime = 0
                        tmms.markettimeday = 0
                        tmms.markettimemonth = 0
                        tmms.tradevolumeday = 0
                        tmms.tradevolumemonth = 0
                        tmms.lastupddate = 0
                        tmms.save()
                        # print('合约做市状态一条记录写入成功！')
                        return HttpResponse("y")
                    else:
                        return HttpResponse("该用户无操作权限！")
            except Exception as e:
                return HttpResponse(e)
        return render(request, 'makemarketpara.html')


# 查看做市状态
def makemarketpara_status(request):
    off = request.GET.get('offset', None)
    lim = request.GET.get('limit', None)
    if lim is None:
        return render(request, 'mmarketparastatus.html')
    else:
        mmp_list = Makemarketstatus.objects.values()
        mmp_list = list(mmp_list)
        result = my_page(mmp_list, lim, off)
        return JsonResponse(result, safe=False)
